﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LOGISTCBUS.Entities;
using LOGISTCBUS.DAO;

namespace LOGISTCBUS.WebUI.Controllers
{
    [HandleError(View = "Error")]
    public class BudgetController : Controller
    {
        public ActionResult Index()
        {
            var user = (User)this.Session["user"];
            if (user == null)
                return RedirectToAction(@"LogOut", @"Account");
            return View();
        }

        public ActionResult Edit(int? id)
        {
            var userLogged = (User)this.Session["user"];
            if (userLogged == null)
                return RedirectToAction(@"LogOut", @"Account");

            if (id.HasValue)
            {
                var budget = new BudgetDAO().selectById(Convert.ToInt32(id));
                this.ViewData[@"budget"] = budget == null ? new Budget() : budget;
            }

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Save(int id)
        {
            var b = id > 0 ? new BudgetDAO().selectById(id) : new Budget();
            var aux = true;

            b.Code = !String.IsNullOrEmpty(Request.Params["code"]) ? Request.Params["code"] : null;
            b.Value = !String.IsNullOrEmpty(Request.Params["value"]) ? Convert.ToDecimal(Request.Params["value"]) : new Nullable<Decimal>();
            b.Trip = !String.IsNullOrEmpty(Request.Params["id_trip"]) ? new Trip() { Id = Convert.ToInt32(Request.Params["id_trip"]) } : null;
            b.Description = !String.IsNullOrEmpty(Request.Params["description"]) ? Request.Params["description"] : null;
            var validateDate = !String.IsNullOrEmpty(Request.Params["validate_date"]) ? Convert.ToDateTime(Request.Params["validate_date"]) : new Nullable<DateTime>();

            if (b.Id > 0)
                aux = new BudgetDAO().update(b);
            else
                aux = new BudgetDAO().insert(b);

            #region customers
            var lstCustomers = new BudgetCustomerDAO().selectByBudget(b.Id);
            if (lstCustomers != null && lstCustomers.Count > 0)
            {
                foreach (var bc in lstCustomers)
                    aux = new BudgetCustomerDAO().delete(bc);
            }

            var customers = Request.Form["customers"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (customers != null && customers.Count > 0)
            {
                foreach (var c in customers)
                {
                    if (!String.IsNullOrEmpty(c))
                    {
                        var bc = new BudgetCustomer()
                        {
                            Budget = b,
                            Customer = new Customer() { Id = Convert.ToInt32(c) },
                            CreateDate = DateTime.Now,
                            ValidateDate = validateDate
                        };
                        aux = new BudgetCustomerDAO().insert(bc);
                    }
                }
            }
            #endregion

            var obj = new
            {
                success = aux,
                message = "Orçamento salvo com sucesso!"
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Search()
        {
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var idTrip = String.IsNullOrEmpty(Request.Params[@"idTrip"]) ? 0 : Convert.ToInt32(Request.Params[@"idTrip"]);
            var pageSize = MvcApplication.pageSize;
            var budgets = new BudgetDAO().select(idTrip, page, pageSize);
            var count = new BudgetDAO().getCount(idTrip);
            var totalPages = (count < pageSize) ? 1 : Math.Ceiling(Convert.ToDecimal(count) / pageSize);
            var lst = new List<object>();

            foreach (var b in budgets)
            {
                var t = new TripDAO().selectById(b.Trip.Id);
                lst.Add(new
                {
                    Id = b.Id,
                    Code = b.Code,
                    Trip = t != null ? t.Code : string.Empty,
                    Value = String.Format("R$ {0:######0.00}", b.Value)
                });
            }

            var obj = new
            {
                data = lst,
                currpage = page,
                totalpages = totalPages,
                totalrecords = count
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete()
        {
            var id = String.IsNullOrEmpty(Request.Params[@"id"]) ? 0 : Convert.ToInt32(Request.Params[@"id"]);
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var aux = true;

            if (id > 0)
            {
                var b = new Budget() { Id = id };
                aux = new BudgetDAO().delete(b);
            }

            var obj = new
            {
                Message = "Registro removido com sucesso!",
                Success = aux,
                Page = page
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteAll()
        {
            var values = Request.Form["ids"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var aux = true;

            var lst = new List<Budget>();
            foreach (var val in values)
                if (!String.IsNullOrEmpty(val))
                    lst.Add(new Budget() { Id = Convert.ToInt32(val) });
            aux = new BudgetDAO().delete(lst);

            var obj = new
            {
                Message = "Registro(s) removido(s) com sucesso!",
                Success = aux
            };

            return Json(obj);
        }
    }
}
